<!--
/**
* @description **企业基本信息
* @author mdong
* @date 2020-05-14
*/
-->
<template>
  <div>
    <a-form-model ref="searchForm"
                  class="index-search-form-model"
                  :model="searchForm"
                  layout="inline"
    >
      <a-form-model-item label="企业名称"
                         prop="name">
        <a-input v-model="searchForm.name"
                 allowClear
                 placeholder="请输入企业名称">
        </a-input>
      </a-form-model-item>
      <a-form-model-item label="所属行业"
                         prop="industryCode">
        <a-select v-model="searchForm.industryCode"
                  allowClear
                  placeholder="请选择所属行业">
          <a-select-option v-for="(item,index) in industryCategoryConst "
                           :key="index"
                           :value="item.value"> {{item.name}}</a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="行政区域">
        <a-cascader v-model="areaList"
                    allowClear
                    :showSearch="true"
                    change-on-select
                    :options="areaConst"
                    :field-names="{ label: 'title', value: 'key', children: 'children' }"
                    expand-trigger="click"
                    placeholder="请选择行政区域"
                    @change="areaChange" />
      </a-form-model-item>
      <a-form-model-item class="top-widget-btn">
        <a-button type="primary"
                  icon="search"
                  shape="round"
                  @click="queryListBycondition">查询</a-button>
        <a-button icon="retweet"
                  shape="round"
                  @click="resetList">重置</a-button>
      </a-form-model-item>
    </a-form-model>
    <div class="enterpriseInformation page">
      <!-- 操作按钮 -->
      <div class="table-opt-btns">
        <a-button type="primary"
                  icon="plus"
                  @click="addEnterpriseInfo">新增</a-button>
        <a-button :disabled="!isSelecte"
                  icon="download"
                  @click="importData">导出</a-button>
        <div style="float:right;margin-right: -10px;">
          <span style="display:inline-block;">
            <a-upload accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                      :file-list="fileList"
                      :before-upload="beforeUpload">
              <a-button title="请按照格式上传">
                <a-icon type="loading" v-if="upLoading"/>
                <a-icon type="upload" v-else/>
                批量导入
              </a-button>
            </a-upload>
          </span>
          <a-button @click="importTemplate"
                    icon="arrow-down">下载导入模板</a-button>
        </div>
      </div>
      <!-- 表格操作 -->
      <a-table :columns="columns"
               :dataSource="tableData"
               bordered
               rowKey="id"
               :customRow="tableCustomRow"
               :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}"
               :loading="tableLoading"
               @change="tableChange"
               :pagination="pagination">
        <div slot="stateConst"
             slot-scope="text,record,index"
             class="tabe-switch">
            <a-popconfirm title="确定要切换状态吗"
                          @confirm="changeState(text, record, index)"
                          okText="是"
                          cancelText="否"
            >
              <a-switch v-if="stateConsts.length"
                        :checked="(stateConsts.length && record.status === stateConsts[0].value) || false"
                        :checked-children="stateConsts.length && stateConsts[0].name"
                        :un-checked-children="stateConsts.length && stateConsts[1].name"
              />
            </a-popconfirm>
        </div>
        <div slot="customAdress"
             slot-scope="text,record"
             class="tabe-button">
          <span>{{record.city}}/{{record.area}} </span>
        </div>
        <div slot="industryCode"
             slot-scope="text,record"
             class="tabe-button">
          <span>{{convertConstName(industryCategoryConst,record.industryCode)}} </span>
        </div>
        <div slot="operation"
             slot-scope="text,record,index"
             class="tabe-button">
          <a-button size="small"
                    type="primary"
                    icon="edit"
                    @click="editData(text, record, index)">编辑</a-button>
         <!--  <a-button size="small"
                    type="primary"
                    icon="eye"
                    @click="viewData(record)">查看</a-button> -->
          <a-button size="small"
                    type="danger"
                    icon="close"
                    @click="delData(text, record, index)">删除</a-button>
        </div>
      </a-table>
      <!-- 表格 -->
    </div>
  </div>
</template>
<script>
import { convertConstName } from '@/utils/filter'
import { post } from '@/request/http'
import { getPageEntinfo, delateEntinfo, disable, enable } from '@/request/api/enterpriseInformationManagement/enterpriseInformation'
import { enterpriseInfoColumns } from '@/utils/columns'
import { getFinalPageNo, deleteInvalidChildren } from '@/utils/index'
import { getDictData, getInfo } from '@/request/api/common'
import { options } from './data'
import { Cascader, Select, Upload, Icon, FormModel, Input, Button, Table, Switch, Popconfirm } from 'ant-design-vue'
export default {
  name: 'enterpriseInformation',
  components: {
    ACascader: Cascader,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    AButton: Button,
    ATable: Table,
    ASelect: Select,
    ASelectOption: Select.Option,
    AUpload: Upload,
    AIcon: Icon,
    ASwitch: Switch,
    APopconfirm: Popconfirm
  },
  watch: {
    'pagination.current': {
      handler: function (current) {
        // 页号改变 重置选中行
        this.selectedRowKeys = []
        this.selectedKeys = ''
      }
    }
  },
  computed: {
    // 是否有选中项
    isSelecte () {
      return this.selectedRowKeys.length > 0
    }
  },
  data () {
    return {
      areaList: [],
      areaConst: [],
      options: options,
      industryCategoryConst: [],
      fileList: [],
      // 表单
      searchForm: {},
      // 角色表头
      columns: enterpriseInfoColumns,
      // 表数据
      tableData: [],
      // 表格选中数据
      selectedRowKeys: [],
      // 选中的id
      selectedKeys: '',
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 是否打开新增和编辑抽屉
      operateVisible: false,
      // 新增编辑
      optType: 'add',
      // 新增和编辑抽屉数据
      operateData: {
      },
      // 导入loading
      upLoading: false,
      // 状态字典
      stateConsts: []
    }
  },
  created () {
    this.queryListByPage()
    this.getDictDataList()
  },
  methods: {
    // table自定义事件
    tableCustomRow (record) {
      return {
        on: { // 事件
          dblclick: (event) => {
            this.viewData(record)
          }
        }
      }
    },
    // 切换状态
    changeState (text, record, index) {
      if (record.status === '2') {
        enable({
          id: record.id,
          status: '1'
        }).then((res) => {
          if (res.code === '0') {
            this.$message.success('企业状态更新成功')
            this.queryDataByPage(this.searchForm)
          }
        }).catch(() => {
        })
      } else {
        disable({
          id: record.id,
          status: '2'
        }).then((res) => {
          if (res.code === '0') {
            this.$message.success('企业状态更新成功')
            this.queryDataByPage(this.searchForm)
          }
        })
      }
    },
    // 转换数据字典
    convertConstName,
    // 获取数据字典
    async  getDictDataList () {
      const params = 'w-001,W-040,Y-002'
      getInfo('Y-001').then((tegionInfo) => {
        if (tegionInfo.code === '0') {
          this.areaConst = deleteInvalidChildren(tegionInfo.data)
        }
      })
      getDictData(params).then((res) => {
        if (res.code === '0') {
          const data = res.data
          // 行业门类
          this.industryCategoryConst = data['w-001']
          this.stateConsts = data['Y-002']
        }
      })
    },
    // 查询列表数据
    queryDataByPage (query) {
      this.tableLoading = true
      const params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        param: query
      }
      getPageEntinfo(params).then((res) => {
        this.tableLoading = false
        if (res.code === '0') {
          this.tableData = res.data.list
          this.pagination.total = res.data.total
        } else {
          this.tableDdata = []
          this.pagination.total = 0
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 默认查询
    queryListByPage () {
      const params = {}
      this.queryDataByPage(params)
    },
    // 表格变动分页查询
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.queryDataByPage(this.searchForm)
      // 查询接口
    },
    // 重置
    resetList () {
      this.areaList = []
      delete this.searchForm.provinceCode
      delete this.searchForm.cityCode
      delete this.searchForm.areaCode
      delete this.searchForm.planCode
      this.$refs.searchForm.resetFields()
      this.pagination.current = 1
      this.queryListByPage()
    },
    // 条件查询
    queryListBycondition () {
      this.pagination.current = 1
      this.queryDataByPage(this.searchForm)
    },
    // 选中行
    selectedRowChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      const selectedKeys = []
      selectedRows.forEach((item) => {
        selectedKeys.push(item.id)
      })
      this.selectedKeys = selectedKeys.length === 1 ? selectedKeys[0] : selectedKeys.join(',')
    },
    addEnterpriseInfo () {
      this.$router.push('/enterpriseInformationManagement/enterpriseInformation/new')
    },
    // 切换查询区域
    // 切换区域
    areaChange (valueArr, selectedOptions) {
      const length = (selectedOptions && selectedOptions.length) || 0
      // this.searchForm.provinceCode = length >= 1 ? selectedOptions[0].key : ''
      // this.searchForm.cityCode = length >= 2 ? selectedOptions[1].key : ''
      // this.searchForm.areaCode = length >= 3 ? selectedOptions[2].key : ''
      // this.searchForm.planCode = length >= 4 ? selectedOptions[3].key : ''
      if (length) {
        const ids = selectedOptions[length - 1].ids || ''
        const idArr = ids.split(',')
        idArr.pop()
        const index = idArr.findIndex((id) => id === valueArr[length - 1]) // 当前最后一级节点的id在ids的哪一个位置
        if (index > -1) {
          this.searchForm.provinceCode = index >= 0 ? idArr[0] : ''
          this.searchForm.cityCode = index >= 1 ? idArr[1] : ''
          this.searchForm.areaCode = index >= 2 ? idArr[2] : ''
          this.searchForm.planCode = index >= 3 ? idArr[3] : ''
        }
      }
    },
    importTemplate () {
      let url = ''
      if (process.env.NODE_ENV === 'development') {
        url = 'http://www.yunids.com:8082/cdhntech-energy/hnEntinfo/loadTemplate'
      } else {
        url = window.location.origin +
          process.env.VUE_APP_BASE_API + '/cdhntech-energy/hnEntinfo/loadTemplate'
      }
      window.open(url)
    },
    importData () {
      let url = ''
      if (process.env.NODE_ENV === 'development') {
        url = `http://www.yunids.com:8082/cdhntech-energy/hnEntinfo/exportExcel?ids=${this.selectedKeys}`
      } else {
        url = window.location.origin +
          process.env.VUE_APP_BASE_API + `/cdhntech-energy/hnEntinfo/exportExcel?ids=${this.selectedKeys}`
      }
      window.open(url)
      // 重置导出选中
      this.selectedRowKeys = []
      this.selectedKeys = ''
    },
    // 上传文件之前校验
    beforeUpload (file) {
      // this.fileList = [...this.fileList, file]
      const isExcel =
        file.type === 'application/xlsx' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt2M = file.size / 1024 / 1024 <= 10
      if (!isExcel) {
        this.$message.error('仅支持Excel格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('大小不能超过 10M!')
        return false
      }
      const formData = new FormData()
      formData.append('file', file)
      // formData.append('path', '/file/customer')
      // this.uploading = true
      const url = '/cdhntech-energy/hnEntinfo/importExcel'
      const requestConfig = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.upLoading = true
      return new Promise((resolve, reject) => {
        post(url, formData, requestConfig).then((res) => {
          this.upLoading = false
          if (res.code === '0') {
            this.$message.success('导入成功!')
            this.queryDataByPage(this.searchForm)
          } else {
            reject(res.msg)
          }
        }).catch((error) => {
          this.upLoading = false
          reject(error)
        })
      })
    },
    handleSearch (dir, value) {
    },
    // 编辑数据
    editData (text, record, index) {
      this.$router.push({
        path: '/enterpriseInformationManagement/enterpriseInformation/edit',
        query: { id: record.id }
      })
    },
    // 查看数据
    viewData (record) {
      this.$router.push({
        path: '/enterpriseInformationManagement/enterpriseInformation/view',
        query: { id: record.id }
      })
    },
    // 删除数据
    delData (text, record, index) {
      this.$confirm({
        title: '删除之后无法恢复，确定要删除数据吗?',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk: () => {
          const params = { id: record.id }
          delateEntinfo(params).then((res) => {
            if (res.code === '0') {
              this.pagination.current = getFinalPageNo(
                this.pagination.total,
                this.pagination.current,
                this.pagination.pageSize,
                1)
              this.queryDataByPage(this.searchForm)
              this.$message.success('删除成功!')
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
</style>
